package com.yanjiali.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

/**
 * @Package: com.yanjiali.com.yanjiali.config
 * @Author: yanjiali
 * @Created: 2025/3/28 18:53
 * 认证授权服务器配置类
 */
@EnableAuthorizationServer
@Configuration
public class AuthorizationConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;    //密码加密

    @Autowired
    private AuthenticationManager authenticationManager; //验证管理器

    @Autowired
    @Qualifier(value = "userServiceDetailsServiceImpl")     //如果测试的 UserDetailsService 没有注解 用于指定
    private UserDetailsService userDetailsService;


    /**
     * 添加第三方客户端
     * 配置对应客户端，然后配置对应客户端拥有的认证方式，再设置toeken参数
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("tenseek-api")
                .secret(passwordEncoder.encode("tenseek-secret"))
                .authorizedGrantTypes("password", "refresh_token")  //添加两种验证方式 password 和 refresh_token
                .accessTokenValiditySeconds(24 * 7200)  //设置token过期时间
                .refreshTokenValiditySeconds(7 * 24 * 7200) //设置refresh_token过期时间
                .scopes("all")
                .and()
                //没有用户交互的上下文，用户程序自行获取token
                .withClient("inside-app")
                .secret(passwordEncoder.encode("inside-secret"))
                .scopes("all")
                .authorizedGrantTypes("client_credentials")
                .accessTokenValiditySeconds(7 * 24 *3600);

        super.configure(clients);
    }

    /**
     * 配置验证管理器，UserDetailService
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService)
                //TODO 设置Jwt后增加，包括后续两个方法
                .tokenStore(jwtTokenStore()) // 设置 token 存储方式，即jwt
                .tokenEnhancer(jwtAccessTokenConverter()); //设置 Token 的增强器（JwtAccessTokenConverter），负责：生成 JWT（编码），解析 JWT（解码），签名验证（使用配置的密钥对）

        super.configure(endpoints);
    }

    /**
     * 创建一个 JWT Token 存储的实现
     * 它不真正"存储"令牌，因为 JWT 是自包含的（所有信息都在令牌本身中）
     * @return
     */
    public TokenStore jwtTokenStore(){
        JwtTokenStore jwtTokenStore = new JwtTokenStore(jwtAccessTokenConverter());
        return jwtTokenStore ;
    }


    /**
     * 创建并配置 JWT 访问令牌转换器
     * 负责令牌的编码(生成JWT)和解码(验证JWT)
     * @return
     */
    public JwtAccessTokenConverter jwtAccessTokenConverter(){
        JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter() ;

        // 读取 classpath 下面的密钥文件
        ClassPathResource classPathResource = new ClassPathResource("tenseek.jks");

        // 获取 KeyStoreFactory
        KeyStoreKeyFactory keyStoreKeyFactory = new
                KeyStoreKeyFactory(classPathResource, "tenseek".toCharArray()) ;

        // 给 JwtAccessTokenConverter 设置一个密钥对
        tokenConverter.setKeyPair(keyStoreKeyFactory.getKeyPair("tenseek", "tenseek".toCharArray()));

        return tokenConverter;
    }
}
